<?php
@include ("phpmailer/function.sendmail.php");
function TImport($md)
{
    $file   = 'source/'.$md.'/functions.php';
    if(is_file($file))
    {
        @include_once $file ;
    }    
}
function ImportClass($cl)
{
    $file   = 'includes/class_'.$cl.'.php';
    if(is_file($file))
    {
        @include_once($file) ;
    }    
}

function debug($message)
{
    $file=$_SERVER['DOCUMENT_ROOT']."/".$GLOBALS['folder_path_root']."docs/log_error.txt";
    $logdata="[".date("d-m-Y/h-i")."-".$_SERVER['REMOTE_ADDR']."] ";
	$logdata.=$message;
	$logdata.="=>".$_SERVER['REQUEST_URI'].">\r\n\r\n";
    $f=@fopen($file,"a");
    if($f)
    {			
        @fwrite($f,$logdata);
        @fclose($f);
    }
}
function csubstr($str,$start,$length)
{
	$str=strip_tags($str);
	$arr=explode(" ",$str);
	$temp="";
	$i=0;
	while(strlen($temp)<$length && $i<count($arr))
	{
		$temp.=$arr[$i++]." ";
	}
	if(strlen($str)>$length)$temp.="...";
	return $temp;
}

function strSplitSub($str,$count)
{
	$return="";
	$countt=0;
	$str=strip_tags($str);
	$length=strlen($str);
	for($i=0;$i<$length;$i++)
	{
		if($str[$i]==" ")
		{
			$countt++;
			if($countt>=$count-1)break;
		}
		$return.=$str[$i];
	}
	if($countt>$count-2)$return.="...";
	return $return;
}

function UpdateOnline()
{
global $ip,$language,$dbsql,$ajax;

	$ip=$_SERVER['REMOTE_ADDR'];
	$datenow=date("Y-m-d H:i:s");
	$url	=$_SERVER['REQUEST_URI'];
	if($ajax===true)
	{
		return;
	}
	$dbsql->query("delete from tblonline where iTime<".(_TIME-60*60),true);
	$sql_select=" select cIp from tblonline where cIp='$ip'";
	$rs=$dbsql->query($sql_select);

	if($dbsql->num_rows($rs)==0)
	{
		$sql_insert="insert into tblonline(cIp,iTime,cUrlEnd,cLanguage,dTimeBegin,iCountPage)
									values('$ip',"._TIME.",'$action','$language','$datenow',0)";
		$dbsql->query($sql_insert,true);
		@addCountRate();
	}else
	{
		$sql_update="update tblonline set
					iTime      = "._TIME.",
                    cUrlEnd    = '$url',
                    iCountPage = iCountPage+1,
                    cLanguage  = '$language'
				where cIp      = '$ip' limit 1";
		$dbsql->query($sql_update,true);
	}
	//$rs=$dbsql->query("CALL UpdateOnline('$ip','$url','$language')",true);
}

function addCountRate()
{
global $ip,$language,$dbsql;

	//reset TODAY:
	$sql_update="update tblconfig set cValue='0',cType='".date("d")."' where cName='ratetoday' and cType!='".date("d")."'";
	$dbsql->query($sql_update,true);

	//reset week:
	$sql_update="update tblconfig set cValue='0',cType='".date("W")."' where cName='rateweek' and cType!='".date("W")."'";
	$dbsql->query($sql_update,true);


	//reset month:
	$sql_update="update tblconfig set cValue='0',cType='".date("m")."' where cName='ratemonth' and cType!='".date("m")."'";
	$dbsql->query($sql_update,true);

	//reset year:
	$sql_update="update tblconfig set cValue='0',cType='".date("Y")."' where cName='rateyear' and cType!='".date("Y")."'";
	$dbsql->query($sql_update,true);

	$sql_update="update tblconfig set cValue=cValue+1 where cName='ratetoday' or cName='rateweek' or cName='ratemonth'
					or cName='rateyear' or cName='ratesite'";
	$dbsql->query($sql_update,true);

}

function CountOnline()
{
    global $language,$dbsql;
	  $timeold=time()-(60*50);
	  
	  $sql_select = "select count(cIp) as count from tblonline  where iTime>$timeold and iCountPage > 0";      
      $rs=$dbsql->query($sql_select);
      $result = $dbsql->fetch_array($rs);
	  return $result["count"];
}

function LoadRateSite()
{
global $language,$dbsql;
	  $sql_select = "select cValue from tblconfig where cName = 'ratesite'";      
      $result=$dbsql->query_fetch($sql_select);
	  return $result['cValue'];
}

function isEmail($email){
    return true;
	return eregi("^([a-zA-Z0-9|-|_]+)(@)([a-zA-Z0-9|-|_]+)(.)([a-zA-Z]+)$", $email);
}

function Exc_AutoLink($str)
{//return $str;
	return $str;
	global $limit_AutoLink;
	for($i=0;$i<count($aKey);$i++)
	{
		$pos=0;
		$count=0;
		while(($pos=stripos($str,$aKey[$i],$pos))!==false)
		{
			$check=true;//echo $pos."|";
			for($j=$pos;$j>0;$j--)
			{				
				if($str[$j]=="<")
				{
					$check=false;
					break;
				}
				if($str[$j]==">")break;
			}
			for($j=$pos;$j<strlen($str);$j++)
			{
				if($str[$j]==">" || (strtolower(substr($str,$j,4))=="</a>"))
				{
					$check=false;
					break;
				}
				if($str[$j]=="<")break;
			}
			if(!$check)
			{
				$pos+=strlen($aKey[$i]);
				continue;
			}
			if($pos>0)$start=$pos-1;
			else $start=$pos;
			$temp1=substr($str,0,$start);
			$temp2=substr($str,$start,strlen($aKey[$i])+5);
			$temp3=substr($str,strlen($temp1.$temp2));
			if(strtolower($temp2)==strtolower($aKey[$i]))
			{
				$temp2.=".";
				$str.=".";
			}
			$se="/(\W|^)(".$aKey[$i].")(\W|$)/i";
			$re='\1<a class="autolink" title="\2" href="'.$aLink[$i].'">\2</a>\3';
			$temp2=preg_replace($se,$re,$temp2,1);	
			$strold=$str;
			$str=$temp1.$temp2.$temp3;
			if($strold!=$str)$count++;
			$pos+=strlen($temp2);
			if($pos>strlen($str))break;			
			if($count>=$limit_AutoLink)break;
		}
	}
	return $str;
}


function ListMenuByPlace($place="all")
{
global $dbsql,$language;
	$place=strtolower($place);
	$iplace=0;
	switch($place)
	{
		case "top":
			$iplace=1;
			break;
		case "left":
			$iplace=2;
			break;
		case "bottom":
			$iplace=3;
			break;
		default:
			$iplace=4;
			break;
	}
		
	$sql_select = "select iId,cName,cUrlString,cType from tblcategory 
			where  (iPlace=$iplace or iPlace=4)  and cLanguage='$language'
			and iStatus='1' order by iOrder";
			
	$rs=$dbsql->query($sql_select);
	$categories=array();
	while ( $result = $dbsql->fetch_array($rs) )
	{
	   if(strpos($result['cUrlString'],".htm")===false)
	   {
	   		$result['cUrlString'].="/";
	   }
	   if($result['cUrlString']=="Home/")
	   {
	   	$result['cUrlString']='';
	   }
	   $categories[] = $result;
	}
	return $categories;
}


function echoLink($url="",$hasEcho=true,$hroot=1)
{
global $root_domain,$folder_path_root;
	if($hroot>0)
	{
		if($url[0]=="/")
		{
			$url=substr($url,1);
		}
		$url= $folder_path_root.$url;
        if($hroot==2)        
        {
            $url=$root_domain.$url;
        }
	}
	if($hasEcho==true)
	{
		echo $url;
	}else 
	{
		return $url;
	}
}

function echoLinkFile($filename,$hasEcho=true)
{
global $root_domain,$folder_path_root,$folder_docs;
	
	$filename  = $folder_path_root.$folder_docs.$filename;
    if($hasEcho)
    {
        echo $filename;
    }else
    {
        return $filename;
    }
}

function echoImgSpam($name='ImgSpamCode',$hasEcho=true)
{
    $html   = '<img id="'.$name.'" src="'.echoLink('Img/spam/'.time().'.gif',false).'"';
    $html  .= ' width="100" height="20" alt="'.getLang('Code Spam').'" style="cursor:pointer"';
    $html  .= ' onclick="this.change()"/>';
    $html  .= '<script>document.getElementById("'.$name.'").change=function(){this.src="'.echoLink('Img/spam/',false).'"+Math.random()+".gif"}</script>';
    if($hasEcho)
    {
        echo $html;
        return;
    }
    return $html;
}

function echoAction($act,$hasEcho=true)
{
    $act    = echoLink('as/'.$act,false);
    if($hasEcho)
    {
        echo $act;
        return;
    }
    return $act;
}

function GetIntroImg($pathfile,$thumb=false,$default=true)
{
global $folder_img_upload;

	$path  = $folder_img_upload;
	if($thumb==true)
	{
        $file     = basename($pathfile);
		$pathfile = str_replace($file,"thumbs/".$file,$pathfile);
		$path    .= $pathfile;
	}else
	{
		$path     .= $pathfile;
	}
    
	if(is_file($path))
	{
		return echoLink($path,false);
	}else if($default==true)
    {
        return echoLink('images/clear.gif',false);
    }
	return false;
}

function GetIntroImg_size($file,$maxW,$maxH)
{
    global $folder_img_upload;
    
    $path               = $folder_img_upload.$file;
    list($imgw,$imgh)   = getimagesize($path);
    $newW               = $imgw;
    $newH               = $imgh;
    if($imgw>$maxW)
    {
        $newW   = $maxW;
        $newH   = $newW*$imgh/$imgw;
    }
    if($newH>$maxH)
    {
        $newH   = $maxH;
        $newW   = $newH*$imgw/$imgh;
    }
    return array($newW,$newH);
}

function Redirect($url)
{
	//header( "HTTP/1.1 301 Moved Permanently" );
	if($GLOBALS['ajax']==true)
	{
		echo '{"act": "Redirect","url": "'.$url.'"}';
		exit;
	}
	header( "Location: $url" ); 
	exit;
}


function LoadAdvertise($place)
{
global $dbsql,$language;

	$advertises=array();
	$sql_select="select cName,cImageLink,cUrlString,iOpenNew from tbladvertise where iPlace='$place' 
                    and cLanguage='$language' and iStatus=1 order by iOrder";
	$rs=$dbsql->query($sql_select);
	while ($result=$dbsql->fetch_array($rs)) {
			$advertises[]=$result;
	}
	return $advertises;
}

function Transfer($url,$sec)
{
	return '<meta http-equiv="REFRESH" content="'.$sec.'; url='.$url.'">';
}

function getConfig($name,$default="",$all=false)
{
    global $dbsql,$language;

	if(is_array($name))
	{
		$loaded=true;
		$configs=array();
		$sql_select="select cName,cValue from tblconfig where cName!='' ";
        if($all==false)
        {
            $sql_select .=" and cLanguage='$language' ";
        } 
        $sql_select.=" and (";
		foreach ($name as $i=>$keyname)
		{
			if($i>0)
            {
                $sql_select.=" or ";
            }
			$sql_select.=" cName='$keyname' ";
            
			if(!isset($GLOBALS['config2_'.$keyname]))
			{
				$loaded=false;
			}
			$configs[$keyname]=$GLOBALS['config2_'.$keyname];
		}
        $sql_select .= ')';
		if($loaded)
		{
			return $configs;
		}
		$rs           = $dbsql->query($sql_select);
		$configs      = array();
		while ($result=$dbsql->fetch_array($rs)) 
        {
			$configs[$result['cName']]           = $result['cValue'];
            $GLOBALS['config2_'.$result['cName']]= $result['cValue'];
		}
		return $configs;
	}

	if(isset($GLOBALS['config2_'.$name]))return $GLOBALS['config2_'.$name];

	$sql_select="select cValue from tblconfig where cName='$name'";
    if($all==false)
    {
        $sql_select.= " and cLanguage='$language'";
    }
	if($result=$dbsql->query_fetch($sql_select))
	{
		$value                    = $result['cValue'];
		$GLOBALS['config2_'.$name]= $value;
	}
	return $value;
}

function getConfigEmail($name)
{
    global $dbsql,$language,$email_admin;
    ImportClass('json');
	$sql_select="select cValue from tblconfig where cName='EmailTemp".$name."' and cLanguage='$language'";
	if($result  =$dbsql->query_fetch($sql_select))
	{
        $result = FJSON::decode($result['cValue']);
        if(!isset($result->email))
        {
            $result->email  = $email_admin;
        }
	}
	return $result;
}

function LoadCategoryRoot($url)
{
    global $dbsql,$language;
    
    $sql_select = "select * from tblcategory where iParentId=0 ";
    if(empty($url))
    {
        $sql_select .= " and cType = 'Home' ";
    }else
    {
        $sql_select .= " and cUrlString='$url' ";
    } 
    $sql_select .=" and cLanguage='$language' ";
    return $dbsql->query_fetch($sql_select);
}

function ListCategoryByParentId($idP)
{
    global $dbsql,$language;
    $idP        = intval($idP);
    $sql_select = "select * from tblcategory where iParentId=$idP and iStatus=1 order by iOrder";
    return $dbsql->load($sql_select);
}

function Split_Page($count_all)
{
    global $page,$posts_per_page,$num_page,$show_page;

	if($page<1)
    {
        $page       = 1;   
    }
    //$posts_per_page = 1;
    
	$limitpage		= array();
	$limitpage[0]	= ($page-1) * $posts_per_page;
	$limitpage[1]   = $posts_per_page;
	$num_page   	= ceil($count_all/$posts_per_page);
    
    $show_page = '<div class="show_page" id="show_page">';
	if ($num_page > 1)
	{
		for ($i=1 ; $i< $num_page + 1 ; $i++)
		{
		   $show_page .= '<a '.(($page==$i)? 'class="se"':"").' href="#'.$i.'" onclick="show_page(this)">'.$i.'</a>';
		}
	}
    $show_page.='</div><div class="clear"></div>';
    $limitpage[3] = $show_page;
    
	return $limitpage;
}

function AjaxTransfer($status,$msg)
{
    ImportClass('json');

    $arrcode    = array("status"=>$status);
    if(is_array($msg))
    {
        foreach($msg as $key => $vl)
        {
            $arrcode[$key] = $vl;
        }
    }else
    {
        $arrcode['msg'] = $msg;
    }
    
    echo FJSON::encode($arrcode);
    exit;
}

function getUrlCatByType($type)
{
    global $dbsql,$language,$urlcatbytypes;
    
    if(isset($urlcatbytypes[$type]))
    {
        return $urlcatbytypes[$type];
    }
    $sql_select = "select cUrlString from tblcategory where cType='$type' and cLanguage='$language'";
    $result     = $dbsql->query_fetch($sql_select);
    $urlcatbytypes[$type]   = $result['cUrlString'];
    return $urlcatbytypes[$type];
}

function ListIntOption($select,$start,$end)
{
	$options="<option value=''>".getLang('select')."</option>";
	$options="";
	for($i=$start;$i<=$end;$i++)
	{
		if($i==$select)
		{
			$options.="<option value='$i' selected>$i</option>";
		}else
		{
			$options.="<option value='$i'>$i</option>";
		}
	}
	return $options;
}

function SelectCat($fields,$type)
{
    global $dbsql,$language;
    
    $sql_select = "select $fields from tblcategory where cType='$type' and cLanguage='$language'";
    return $dbsql->query_fetch($sql_select);
}

function ListCatChild($fields,$idP,$isroot=false,$limit=0,$table='tblcategory',$split=false)
{
    global $dbsql,$language;
    if($isroot==false && intval($idP)==0)return array();
    
    $sql_where  = " from $table where iParentId='$idP' and iStatus=1 and cLanguage='$language'";
    if($split)
    {
        $sql_select = "select count(iId) as count ".$sql_where;
        $result     = $dbsql->query_fetch($sql_select);
        list($lf,$la)= Split_Page($result['count']);
        $sql_select = "select $fields ".$sql_where." order by iOrder limit $lf,$la ";
    }else
    {
        $sql_select = "select $fields ".$sql_where." order by iOrder";
        if($limit>0)
        {
            $sql_select .= " limit $limit ";
        }
    } 
    return $dbsql->load($sql_select);
}

function getLinkParentCat($idP)
{
     global $dbsql,$language,$urlsParentCats;
    
    if(isset($urlsParentCats[$idP]))
    {
        return $urlsParentCats[$idP];
    }
    $sql_select = "select cUrlString,iParentId from tblcategory where iId='$idP' and cLanguage='$language'";
    $result     = $dbsql->query_fetch($sql_select);
    if($result['iParentId']>0)
    {
        $urlP   = getLinkParentCat($result['iParentId']).'/';
    }
    
    $urlsParentCats[$idP]   = $urlP.$result['cUrlString'];
    return $urlsParentCats[$idP];
}


function splitPrice($number)
{
    while (true) {
        $replaced = preg_replace('/(-?\d+)(\d\d\d)/', '$1,$2', $number);
        if ($replaced != $number) {
            $number = $replaced;
        } else {
            break;
        }
    }
    return $number;
}

function getPriceClient($price,$rel=false,$sameDisplay=true)
{
    if($price==0)
    {
        return;
    }
	$pren=getConfig(array('UnitInput','UnitDisplay','CurrencyUSD'));

	if($rel)
	{
		return $price.' '.$pren['UnitInput'];
	}

	if($pren['CurrencyUSD']==0)$pren['CurrencyUSD']=1;
	if($sameDisplay==false)
	{
		$pren['UnitDisplay']=($pren['UnitDisplay']=='USD')? 'VND' : 'USD';
	}
	if($pren['UnitInput']!=$pren['UnitDisplay'])
	{
		if($pren['UnitInput']=='USD') {
			$price=$price*$pren['CurrencyUSD'];
		}else if($pren['UnitInput']=='VND'){
			$price=$price/$pren['CurrencyUSD'];
		}
	}
	$price=preg_replace("(([0-9]*)(.)([0-9]{2})([0-9]*))","$1$2$3",$price);
	return splitPrice($price).' '.$pren['UnitDisplay'];
}

function productCatBanner()
{
    global $module;
    $show           = ($module=="product")? true: false;
    $show           = true;
    $listcat        = ListCatChild('cName,cUrlString,cImage',0,true,7,'tblproduct_category');
    $linkproroot    = getUrlCatByType('product');
    $html        = '<div id="productcathead" style="display:'.(($show)? '': 'none').'">';
    //$html       .= '<div class="bglayer"></div>';
    $html       .= '<div class="productcathead">';    
    foreach($listcat as $cat)
    {
        $link   = $linkproroot.'/'.$cat['cUrlString'];
        $html .= '<a href="'.echoLink($link,false).'">';
        $html .= '<span class="img"><img src="'.GetIntroImg($cat['cImage'],true).'" height=100% border=0></span>';
        $html .= '<span class="t">'.$cat['cName'].'</span>';
        $html .= '</a>';
    }
    $html      .= '</div></div>';
    return $html;
}

function ListImageBanner($name='sl')
{
    global $dbsql,$language;
    
    $sql_select = "select * from tblimages where cType='banner' order by rand()";
    $rs         = $dbsql->query($sql_select);
    $script     = 'var '.$name.'=new TrSlide();';
    while($result   = $dbsql->fetch_array($rs))
    {
        $script.= $name.'.add("'.GetIntroImg($result['cImage']).'");';
    }
    return $script;
}

?>